package com.sx.gongzhong.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.compress.Luban;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sx.gongzhong.BaseActivity;
import com.sx.gongzhong.MyApplication;
import com.sx.gongzhong.R;
import com.sx.gongzhong.model.GenderBean;
import com.sx.gongzhong.model.MsgEvent;
import com.sx.gongzhong.model.PhotoBean;
import com.sx.gongzhong.model.UserInfoBean;
import com.sx.gongzhong.net.MyRxBus;
import com.sx.gongzhong.net.ServiceFactory;
import com.sx.gongzhong.param.UpdateUserInfo;
import com.sx.gongzhong.pest.UploadFilePest;
import com.sx.gongzhong.pest.UpdateUserInfoPest;
import com.sx.gongzhong.utils.BaseUtil;
import com.sx.gongzhong.utils.ToastUtils;
import com.sx.gongzhong.view.IVoidView;
import com.sx.gongzhong.view.UploadFileView;
import com.sx.gongzhong.widget.ClearEditText;
import com.sx.gongzhong.widget.LoadDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import xiaofei.library.datastorage.DataStorageFactory;
import xiaofei.library.datastorage.IDataStorage;

/**个人用户信息修改
 * Created by admin on 2017/12/29.
 */

public class UserInfoActivity extends BaseActivity implements IVoidView, UploadFileView {
    @BindView(R.id.et_myNikename)
    ClearEditText et_myNikename;
    @BindView(R.id.rbt_Man)
    RadioButton rbt_Man;
    @BindView(R.id.rbt_Woman)
    RadioButton rbt_Woman;
    @BindView(R.id.tv_myborndate)
    TextView tvMyborndate;
    @BindView(R.id.et_myintroduce)
    EditText etMyintroduce;
    @BindView(R.id.iv_head)
    ImageView ivHead;

    private String path;
    private UserInfoBean userBean;
    private UpdateUserInfo userInfo = new UpdateUserInfo();
    @Override
    public void setUI(Bundle savedInstanceState) {
        setContentView(R.layout.activity_userinfo);
        ButterKnife.bind(this);
        setTitleName("信息修改");
        setTitleRight("保存");

        userBean = MyApplication.instance.userBean;
        if (userBean != null){
            et_myNikename.setText(userBean.name);
            tvMyborndate.setText(userBean.birthday);
            etMyintroduce.setText(userBean.selfIntroduction);
            if (userBean.gender != null){
                if (userBean.gender.code.equals("male")){
                    rbt_Man.setChecked(true);
                }else if (userBean.gender.code.equals("female")) {
                    rbt_Woman.setChecked(true);
                }
            }
            if (userBean.header != null && !BaseUtil.isEmpty(userBean.header.getPath())){
                RequestOptions options = new RequestOptions().centerCrop()
                        .placeholder(R.mipmap.img_head_default)
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                        .circleCrop()
                        .error(R.mipmap.img_head_default);
                Glide.with(this)
                        .load(ServiceFactory.getUrl(userBean.header.getPath()))
                        .apply(options)
                        .into(ivHead);
            }
        }
    }

    @OnClick({R.id.iv_head,R.id.tv_right, R.id.tv_myborndate})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_head:
                PictureSelector.create(this)
                        .openGallery(PictureMimeType.ofImage())
                        .selectionMode(PictureConfig.SINGLE)
                        .maxSelectNum(1)
                        .previewImage(true)// 是否可预览图片
                        .enableCrop(true)
                        .compress(true)
                        .compressGrade(Luban.CUSTOM_GEAR)
                        .compressMaxKB(200)//压缩最大值kb compressGrade()为Luban.CUSTOM_GEAR有效 int
                        .forResult(PictureConfig.CHOOSE_REQUEST);
                break;
            case R.id.tv_myborndate:
                BaseUtil.createDataPop(this,tvMyborndate);
                break;
            case R.id.tv_right:
                userInfo.name = et_myNikename.getText().toString().trim();
                userInfo.genderCode  = "unknown";
                if (rbt_Man.isChecked()){
                    userInfo.genderCode  = "male";
                }else if (rbt_Woman.isChecked()){
                    userInfo.genderCode  = "female";
                }
                userInfo.birthday = tvMyborndate.getText().toString().trim();
                userInfo.selfIntroduction = etMyintroduce.getText().toString().trim();
                LoadDialog.show(UserInfoActivity.this,"保存中...");
                if (!BaseUtil.isEmpty(path)){
                    List<File> files = new ArrayList<>();
                    files.add(new File(path));
                    new UploadFilePest(this).uploadFile(this,files);
                }else {
                    new UpdateUserInfoPest(this).updateUserInfo(this,userInfo);
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                List<LocalMedia> picUrls = PictureSelector.obtainMultipleResult(data);
                if (!picUrls.isEmpty()) {
                    for (LocalMedia localMedia : picUrls) {
                        path = localMedia.getCompressPath();
                        RequestOptions options = new RequestOptions().centerCrop()
                                .placeholder(R.mipmap.img_head_default)
                                .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                                .circleCrop()
                                .error(R.mipmap.img_head_default);
                        Glide.with(this)
                                .load(path)
                                .apply(options)
                                .into(ivHead);
                    }
                }
            }
        }
    }

    @Override
    public void showError(String message) {
        LoadDialog.dismiss(UserInfoActivity.this);
        ToastUtils.showToast(UserInfoActivity.this,message);
    }

    @Override
    public void uploadSuccess(List<PhotoBean> beans) {
        if (userBean.header != null && !BaseUtil.isEmpty(userBean.header.getId())){
            userInfo.removeIds = userBean.header.getId();
        }
        userBean.header = beans.get(0);
        userInfo.headerId = beans.get(0).getId();
        new UpdateUserInfoPest(this).updateUserInfo(this,userInfo);
    }

    @Override
    public void voidView(String s) {
        userBean.name = userInfo.name;
        GenderBean gender = new GenderBean();
        gender.code = userInfo.genderCode;
        userBean.gender = gender;
        userBean.birthday = userInfo.birthday;
        userBean.selfIntroduction = userInfo.selfIntroduction;
        MyApplication.instance.userBean = userBean;
        IDataStorage dataStorage = DataStorageFactory.getInstance( getApplicationContext(),
                DataStorageFactory.TYPE_DATABASE);
        dataStorage.storeOrUpdate(userBean,getPackageName());
        MyRxBus.get().post(new MsgEvent("MyFragment",1,null));
        LoadDialog.dismiss(UserInfoActivity.this);
        ToastUtils.showToast(UserInfoActivity.this,"修改成功");
    }
}
